package cn.tedu.coolshark.filter;

import cn.tedu.coolshark.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter",urlPatterns ={"/admin.html","/insertProduct.html","/index.html"} )
public class MyFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        //初始化时执行
    }

    public void destroy() {//销毁时执行
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //判断是否登录
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //得到会话对象
        HttpSession session = req.getSession();
        //获取登录成功时保存的用户对象
        User u = (User) session.getAttribute("u");
        if (u != null) {//代表登录过
            chain.doFilter(request, response);//允许访问资源
        } else {//代表没有登录过
            //告诉客户端 重定向到登录页面
            resp.sendRedirect("/login.html");
        }
    }
}
